package com.wxw.BaseLibrary.element;

import android.graphics.Color;
import com.wxw.BaseLibrary.component.DataGridHeadCell;
import com.wxw.BaseLibrary.component.DataGridViewRow;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by david on 2015-12-18.
 */
public class DataGridJsonDataObject implements IDataGridDataObject {
    private List<String> heads = new ArrayList<String>();
    private List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
    private JSONArray jsonArray = null;

    public DataGridJsonDataObject(JSONArray jsonArray) {
        this.jsonArray = jsonArray;
        parseJson();
    }

    private void parseJson() {
        if (this.jsonArray == null) {
            return;
        }
        try {
            JSONArray names = jsonArray.getJSONObject(0).names();
            int cols = names.length();
            heads.clear();
            for (int i = 0; i < cols; i++) {
                heads.add(names.getString(i));
            }
            rows.clear();
            for (int i = 0; i < jsonArray.length(); i++) {
                Map<String, Object> row = new HashMap<String, Object>();
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                for (int j = 0; j < cols; j++) {
                    row.put(names.getString(j), jsonObject.get(names.getString(j)));
                }
                rows.add(i, row);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public int size() {
        return rows != null ? rows.size() : 0;
    }

    public void setHeads(List<String> heads) {
        this.heads = heads;
    }

    @Override
    public List<String> getHeads() {
        return this.heads;
    }

    @Override
    public String getValue(int row, String key) {
        Object o = getObjectValue(row, key);
        return o==null?"":o.toString();
    }

    @Override
    public Object getObjectValue(int row, String key) {
        if (rows == null || rows.size() <= 0) {
            return "";
        }
        if (row < 0 || row >= rows.size()) {
            return "";
        }
        if (!rows.get(row).containsKey(key)) {
            return "";
        }
        Object o = rows.get(row).get(key);
        return o;
    }
}
